<?php
//注册的model文件 
//author speakphp.com
class MemberModel extends CommonModel {
    public function __construct(){
        parent::__construct();
    }
	//用户的基本信息返回给客户端，其中有一些参数是加密的
	public function getUserInfoToApp($uid){
		$returnData = array();
		$info = $this->getInfoByUid($uid);
		return $this->returnUserParams($info);
	}
	//客户端返回一些用户的参数
	function returnUserParams($info){
		$returnData['uid'] = auth_code($info['uid'] , "ENCODE");
		$returnData['username'] = $info['username'];
		$returnData['uname'] = $info['uname'];
		$returnData['sex'] = $info['sex'];
		$returnData['score'] = $info['score'];
		$returnData['money'] = $info['money'];
		$returnData['sign_days'] = $info['sign_days'];
		$returnData['ip'] = $info['ip'];
		return $returnData;
	}
	//根据uid查询用户的基本信息
	public function getInfoByUid($uid){
		return M("Member")->where("uid='{$uid}'")->find();
	}
    //注册接口
    function register($params = array() ){
		$username = $params['username'];
		$passwd = $params['passwd'];
		$repasswd = $params['repasswd'];
		if(!checkUsername($username)){
			return array("status"=>0 , 'message'=>'用户名格式不对,必须是字母开头6-16位');
		}
		if(!checkPasswd($passwd)){
			return array("status"=>0 , 'message'=>'密码格式不对,必须是字母开头6-16位');
		}
		if($passwd != $repasswd){
			return array("status"=>0 , 'message'=>'2次密码不相同');
		}
		$infoData = $this->queryByUsername($username) ; 
		if($infoData){
			return array("status"=>0 , 'message'=>"用户名{$username}已经被占用~~");
		}
		$MemberModel = M("Member");
		$success = false ;
		$registerData = array(
			'username'=>$username ,
			'passwd'=>md5($passwd),
			'regdate'=>time(),
			'ip'=>get_client_ip(),		
		);
		$MemberModel->startTrans();
		$uid= $MemberModel->data($registerData)->add();
		$success = ($uid > 0 )?true:false ;
		if(C("app_member_register_money") > 0 ){
			$moneyData = array(
					'uid'=>$uid ,
					'money'=>C("app_member_register_money") ,
					'add_time'=>time(),
					'remark'=>'注册赠送金钱￥'.C("app_member_register_money"),
					'action'=>1,
			);
			$moneyId = M("Member_money_log")->data($moneyData)->add();
			$success = ($moneyId > 0 )?true:false;
		}
		if(C("app_member_register_score") > 0 ){
			$ScoreData = array(
					'uid'=>$uid ,
					'score'=>C("app_member_register_score") ,
					'add_time'=>time(),
					'remark'=>'注册赠送积分'.C("app_member_register_score"),
					'action'=>1,
			);
			$scoreId = M("Member_score_log")->data($ScoreData)->add();
			$success = ($moneyId > 0 )?true:false;
		}
		if ($success){
		// 提交事务
			$MemberModel->commit();
			return array('status'=>1 , 'message'=>"注册成功"  , 'info'=>$this->getUserInfoToApp($uid));
		}else{
			// 事务回滚
			$MemberModel->rollback();
			return array('status'=> 0 , 'message'=>"网络繁忙请稍后~~~" );
		}
		
    }
    //登录接口
    function login($params  = array()){
    	$username = $params['username'];
    	$passwd = $params['passwd'];
    	if(!checkUsername($username)){
    		return array("status"=>0 , 'message'=>'用户名格式不对,必须是字母开头6-16位');
    	}
    	if(!checkPasswd($passwd)){
    		return array("status"=>0 , 'message'=>'密码格式不对,必须是字母开头6-16位');
    	}
    	$infoData = $this->queryByUsernamePwd($username, $passwd);
    	if(!$infoData){
    		return array("status"=>0 , 'message'=>'用户名或者是密码错误');
    	}
    	$resData = $this->checkExpire($infoData);
    	if($resData['status'] != 1 ){
    		return array("status"=>0 , 'message'=>$resData['message']);
    	}
    	return array('status'=> 1 , 'message'=>'登录成功' , 'info'=>$this->getUserInfoToApp($infoData['uid']));
    }
    //修改密码
    function editPwd($params = array() ){
    	$info = $this->getInfoByUid($params['uid']);
    	if(!$info){
    		return array('status'=> 0 , 'message'=>'非法操作');
    	}
    	$expireData = $this->checkExpire($info);
    	if($expireData['status'] != 1 ){
    		return array('status'=> 0 , 'message'=>$expireData['message']);
    	}
    	if(!checkPasswd($params['old_pwd'])){
    		return array('status'=> 0 , 'message'=>"密码格式不对,必须是字母开头6-16位");
    	}
    	if(!checkPasswd($params['new_pwd'])){
    		return array('status'=> 0 , 'message'=>"新密码格式不对,必须是字母开头6-16位");
    	}
    	if($params['new_pwd'] != $params['re_pwd']){
    		return array('status'=> 0 , 'message'=>"2次密码不相同");
    	}
    	if(md5($params['old_pwd']) != $info['passwd']){
    		return array('status'=> 0 , 'message'=>"密码错误请重新尝试~~");
    	}
    	$rows = M("Member")->where("uid = '{$params['uid']}'")->save(array('passwd'=>md5($params['new_pwd'])));
    	if($rows >= 1 ){
    		//插入日志表
    		M("Member_log")->add(array(
    			'uid'=>$params['uid'],
    			'message'=>"用户{$info['username']}修改密码成功",
    			'add_time'=>time()
    		));
    		return array('status'=> 1 , 'message'=>"密码修改成功");
    	}
    	return array('status'=> 0 , 'message'=>"网络繁忙请稍后，你可能没有修改数据");
    }
    //修改基本信息接口
    function editInfo($params = array() ){
    	$info = $this->getInfoByUid($params['uid']);
    	if(!$info){
    		return array('status'=> 0 , 'message'=>'非法操作');
    	}
    	$expireData = $this->checkExpire($info);
    	if($expireData['status'] != 1 ){
    		return array('status'=> 0 , 'message'=>$expireData['message']);
    	}
    	if(!in_array($params['sex'] , array(0 , 1 ,2 ))){
    		return array('status'=> 0 , 'message'=>"请填写正确的性别");
    	}
    	$updateData = array(
    		'sex'=>$params['sex'],	
    		'uname'=>$params['uname'],
    	);
    	$rows = M("Member")->where("uid = '{$params['uid']}'")->save($updateData);
    	if($rows >= 1 ){
    		//插入日志表
    		M("Member_log")->add(array(
    		'uid'=>$params['uid'],
    		'message'=>"用户{$info['username']}修改了基本资料",
    		'add_time'=>time()
    		));
    		return array('status'=> 1 , 'message'=>"资料修改成功");
    	}
    	return array('status'=> 0 , 'message'=>"网络繁忙请稍后，你可能没有修改数据");
    }
    //修改图像
    public function editPic($params = array() ){
    	$info = $this->getInfoByUid($params['uid']);
    	if(!$info){
    		return array('status'=> 0 , 'message'=>'非法操作');
    	}
    	$expireData = $this->checkExpire($info);
    	if($expireData['status'] != 1 ){
    		return array('status'=> 0 , 'message'=>$expireData['message']);
    	}
    	if($_FILES['pic']['name'] == '' ){
    		return array('status'=> 0 , 'message'=>'请上传图片');
    	}
    	import('ORG.Net.UploadFile');
    	$upload = new UploadFile();// 实例化上传类
    	$upload->maxSize  = 3145728 ;// 设置附件上传大小 3M
    	$upload->allowExts  = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
    	$upload->savePath =  __ROOTPATH__.'/Data/Upload/User/';// 设置附件上传目录
    	$upload->autoSub = true;//使用子目录保存上传文件
    	$upload->subType = 'date';//使用日期模式创建子目录
    	$upload->dateFormat = 'Ymd';//设置子目录日期格式
    	if(!$upload->upload()) {// 上传错误提示错误信息
    		return array('status' => 0 , 'message'=> $upload->getErrorMsg());
    	}else{// 上传成功 获取上传文件信息
    		$info =  $upload->getUploadFileInfo();
    	}
    	$filename = $info[0]['savename'];
    	if(!$filename){
    		return array('status'=> 0 , 'message'=>'无法获取到上传图片的信息');
    	}
    	$row =  M("Member")->where(array('uid'=>$params['uid']))->save(array('pic'=>$filename));
    	if($row){
    		return array('status'=> 1, 'message'=>'修改成功' );
    	}
    	return array('status'=> 0 , 'message'=>'网络繁忙请稍后~~');
    }
    //排行榜接口
    public function ranking($type){
    	$type = (!in_array($type, array(1,2)))?1:$type;
    	//1 ：积分排行榜 2：钱排行榜
    	$num = 100 ;
    	if($type == 1 ){
    		$res = $this->scoreList($num);
    	}elseif($type == 2 ){
    		$res = $this->moneyList($num);
    	}
    	return $res ;
    }
    //积分数据排行榜前几名的
    public function scoreList($num){
    	$data = S("scoreList" );
    	if($data && !empty($data)){
    		return $data;
    	}
       	$sql="select username , score,
		case 
		when @prevRank = score then @curRank
		when @prevRank := score then @curRank := @curRank+1
		end as rank 
		from {$this->tablePrefix}member as p ,
		(select @curRank := 0 , @prevRank := null )r
		order by score desc limit $num";
    	$info = M("Member")->query($sql);
    	S("scoreList" , $info , 24*3600 , 'File' );
    	if($info){
    		return array('status'=>1 , 'message'=>"获取成功" , 'list'=>$info);
    	}
    	return array('status'=>0 , 'message'=>"获取失败" , 'list'=>array());
    }
    //金钱排行榜
    function moneyList($num ){
    	$data = S("moneyList" );
    	if($data && !empty($data)){
    		return $data;
    	}
    	$sql="select username , money,
    	case
    	when @prevRank = score then @curRank
    	when @prevRank := score then @curRank := @curRank+1
    	end as rank
    	from {$this->tablePrefix}member as p ,
    	(select @curRank := 0 , @prevRank := null )r
    	order by money desc limit $num";
    	$info = M("Member")->query($sql);
    	S("moneyList" , $info , 24*3600 , 'File' );
    	if($info){
    		return array('status'=>1 , 'message'=>"获取成功" , 'list'=>$info);
    	}
    	return array('status'=>0 , 'message'=>"获取失败" , 'list'=>array());
    }
    
    //获取用户的信息，主要是根据uid，用户已经登录成功进行获取，最后返回给客户端
    function getLoginInfoByUid($uid){
    	$info = $this->getInfoByUid($uid);
    	if(!$info){
    		return array('status'=> 0  , 'message'=>'暂时没查询到此用户的信息');
    	}
    	$expireData = $this->checkExpire($info);
    	if(!$expireData['status']){
    		return array('status'=> 0 , 'message'=>$expireData['message']);
    	}
    	return array('status'=>1 , 'message'=>'获取成功' , 'info'=>$this->returnUserParams($info)) ; ;
    	
    }
    //根据后台设置的有效期判断用户和状态判断用户是否有效
    public function checkExpire($res){
    	if(!$res){
    		return array('status'=> 0  , 'message'=>'此用户已经被禁用');
    	}
    	if($res['status'] != 1 ){
    		return array('status'=> 0  , 'message'=>'此用户已经被禁用');
    	}
    	if($res['expire'] > 0 ){
    		if(time() > $res['expire']){
    			return array('status'=> 0  ,'message'=>'用户已经过期'  ) ;
    		}
    	}
    	return array('status'=>1 , 'message'=>'用户可以正常使用');
    } 
    //根据用户名查询用户是否存在
    public function queryByUsername($username){
    	return M("Member")->where("username='{$username}'")->find();
    }
    //根据用户名和密码查询是否存在
    public function queryByUsernamePwd($username , $passwd ){
    	$passwd = md5($passwd);
    	return M("Member")->where("username='{$username}' AND passwd = '{$passwd}' ")->find();
    }
   
}
